<?php

namespace App\Imports;

use App\Models\Dorm;
use App\Models\DormMeterRecord;
use App\Models\MeterType;
use App\Models\Period;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;


class DormMeterRecordImport implements ToCollection
{
    public $total = 0;
    public $success = 0;
    public $fail = 0;
    public $fail_dorms = "";
    public $ignore = 0;
    public $ignore_dorms = "";

    public function __construct()
    {
        $this->total = 0;
        $this->success = 0;
        $this->fail = 0;
        $this->ignore = 0;
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $rows)
    {
        $i = 0;
        $user_id = optional(\Auth::user())->id;
        foreach ($rows as $row) {
            if ($i++ > 0) {
                $this->total++;
                try {
                    $dormId = trim($row[0]);
                    $periodId = trim($row[1]);
                    $meterTypeId = trim($row[2]);
                    $meterReading = $row[3];
                    $readingDate = $row[4];
                    //这个数字判断很重要，否则将数字开头的房号如11#1D105这样的值给find方法使用，会直接查到id=11的住房信息，导致各种奇怪的错误。
                    if (is_numeric($dormId)) {
                        $dorm = Dorm::query()->find($dormId);
                    } else {
                        if (auth()->check()) {
                            $dorm = Dorm::query()->where('code', $dormId)->where('company_id', auth()->user->company_id)->first();
                        } else {
                            $dorm = Dorm::query()->where('code', $dormId)->first();
                        }
                    }
                    if (!$dorm) {
                        $this->ignore++;
                        $this->ignore_dorms .= "<br> [$i $dormId 查不到]";
                        continue;
                    }

                    $period = Period::query()->find($periodId);
                    if (!$period) {
                        $period = Period::query()->where('name', $row[1])->first();
                        if (!$period) {
                            $this->ignore++;
                            $this->ignore_dorms .= "<br> [$i $period 查不到]";
                            continue;
                        }
                    }
                    $meterType = MeterType::query()->find($meterTypeId);
                    if (!$meterType) {
                        $meterType = MeterType::query()->where('name', $meterTypeId)->first();
                        if (!$meterType) {
                            $this->ignore++;
                            $this->ignore_dorms .= "<br> [$i $meterType 查不到]";
                            continue;
                        }
                    }
                    $readingDate = Carbon::instance(Date::excelToDateTimeObject($readingDate));

                    $meter = $dorm->meters->where('meter_type_id', $meterType->id)->where('active', 1)->first();
                    //$meter = DormMeter::query()->where([['dorm_id',$dorm->id],['meter_type_id',$meterType->id],['active', 1]])->first();
                    if ($meter) {
                        $lastReadingDate = Carbon::parse($meter->last_reading_date);
                        $day_span = $readingDate->diffInDays($lastReadingDate);
                        if ($meter->last_reading <= $meterReading && $day_span >= 1) {
                            $rec = DormMeterRecord::query()->where([['dorm_id', $dorm->id], ['meter_type_id', $meterType->id], ['period_id', $period->id]])->first();
                            if ($rec) {
                                $rec->user_id = $user_id;
                                $rec->reading = $meterReading;
                                $rec->meter_reading_date = $readingDate;
                                $rec->day_span = $day_span;
                                $rec->consume = $meterReading - $rec->prev_meter_reading;
                                $rec->save();
                            } else {
                                DormMeterRecord::query()->create([
                                    'dorm_id' => $dorm->id,
                                    'meter_type_id' => $meterType->id,
                                    'period_id' => $period->id,
                                    'dorm_meter_id' => $meter->id,
                                    'user_id' => $user_id,
                                    'prev_meter_reading' => $meter->last_reading,
                                    'meter_reading' => $meterReading,
                                    'meter_reading_date' => $readingDate,
                                    'day_span' => $day_span,
                                    'consume' => $meterReading - $meter->last_reading,
                                    'remark' => '从excel表导入'
                                ]);
                            }
                            $meter->last_reading = $meterReading;
                            $meter->last_reading_date = $readingDate;
                            $meter->save();
                            $this->success++;
                        } else {
                            $this->ignore++;
                            if ($day_span < 1) {
                                $this->ignore_dorms .= "<br> [$i $dormId 跨度 $day_span < 1天]";
                            } else {
                                $this->ignore_dorms .= "<br> [$i $dormId 抄表 上期 $meter->last_reading > 本期 $meterReading]";
                            }
                        }
                    } else {
                        $this->ignore++;
                        $this->ignore_dorms .= "<br> [$i $dormId $meterTypeId 表未启用]";
                    }
                } catch (\Exception $exception) {
                    $this->fail++;
                    $this->fail_dorms .= "<br> $dormId";
                }
            }
        }
    }
}
